package com.tim.app.ui.activity.person_center;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.google.gson.Gson;
import com.qiyukf.unicorn.api.ConsultSource;
import com.qiyukf.unicorn.api.SavePowerConfig;
import com.qiyukf.unicorn.api.StatusBarNotificationConfig;
import com.qiyukf.unicorn.api.UICustomization;
import com.qiyukf.unicorn.api.Unicorn;
import com.qiyukf.unicorn.api.YSFOptions;
import com.qiyukf.unicorn.api.YSFUserInfo;
import com.tim.app.R;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.Article;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.HelpMessageListResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.activity.selected.ArticleDetailActivity;
import com.tim.app.ui.adapter.personal.HelpMessageAdapter;
import com.tim.app.ui.view.HelpCenterHeadView;
import com.tim.app.ui.view.SpecialDetialHeadView;
import com.tim.app.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 帮助中心
 */
public class HelpCenterActivity extends BaseActivity implements BaseRecyclerAdapter.OnItemClickListener {

    private static final String TAG = "HelpCenterActivity";

    private ImageView ivBack;
    private TextView tvFeedback;

    private WrapRecyclerView wrvHelpMessage;
    private EmptyLayout emptyLayout;
    private HelpMessageAdapter adapter;
    private List<HelpMessageListResult.Res.Data> dataList;

    private HelpCenterHeadView headView;

    public static void start(Context context) {
        Intent intent = new Intent(context, HelpCenterActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onBeforeSetContentLayout() {
        super.onBeforeSetContentLayout();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_help_center;
    }

    @Override
    public void initView() {
        tvFeedback = (TextView) findViewById(R.id.tvFeedback);
        ivBack = (ImageView) findViewById(R.id.ivBack);
        ivBack.setOnClickListener(this);
        wrvHelpMessage = (WrapRecyclerView) findViewById(R.id.wrvHelpMessage);

        wrvHelpMessage.setOverScrollMode(View.OVER_SCROLL_NEVER);

        emptyLayout = new EmptyLayout(this, wrvHelpMessage);
        emptyLayout.setEmptyButtonShow(false);
        emptyLayout.showLoading();
        emptyLayout.setEmptyDrawable(R.drawable.ic_empty_friend);


        headView = (HelpCenterHeadView) LayoutInflater.from(this).inflate(R.layout.help_center_head_view, null);
        wrvHelpMessage.addHeaderView(headView);

        if (dataList == null) {
            dataList = new ArrayList<>();
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        wrvHelpMessage.setLayoutManager(layoutManager);

        adapter = new HelpMessageAdapter(this, dataList);
        adapter.setOnItemClickListener(this);
        wrvHelpMessage.setAdapter(adapter);
        emptyLayout.setEmptyText("还没有任何帮助信息", "");

        tvFeedback.setOnClickListener(this);
    }

    @Override
    public void initData() {
        API_User.ins().getHelpMessage(TAG, refreshCallback);
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                HelpMessageListResult result = new Gson().fromJson(resultValue, HelpMessageListResult.class);
                dataList.clear();
                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist()) {
                        dataList.addAll(result.getRes().getArraylist());
                        adapter.notifyDataSetChanged();
                    }

                    if (dataList.size() == 0) {
                        emptyLayout.showEmpty();
                    } else {
                        emptyLayout.showContent();
                    }
                } else {
                    emptyLayout.showEmpty();
                }
            } else {
                emptyLayout.showEmptyOrError(errCode);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvFeedback:
                String title = "茉莉";
                /**
                 * 设置访客来源，标识访客是从哪个页面发起咨询的，
                 * 用于客服了解用户是从什么页面进入三个参数分别为
                 * 来源页面的url，来源页面标题，来源页面额外信息（可自由定义）。
                 * 设置来源后，在客服会话界面的"用户资料"栏的页面项，可以看到这里设置的值。
                 */
                ConsultSource source = new ConsultSource("", title, "custom information string");
                /**
                 * 请注意： 调用该接口前，应先检查Unicorn.isServiceAvailable()，
                 * 如果返回为false，该接口不会有任何动作
                 *
                 * @param context 上下文
                 * @param title   聊天窗口的标题
                 * @param source  咨询的发起来源，包括发起咨询的url，title，描述信息等
                 */
                Unicorn.updateOptions(initOptions());
                Unicorn.openServiceActivity(HelpCenterActivity.this, title, source);
                break;
        }
    }

    // 如果返回值为null，则全部使用默认参数。
    private YSFOptions initOptions() {
        YSFOptions options = new YSFOptions();
        options.statusBarNotificationConfig = new StatusBarNotificationConfig();
        options.savePowerConfig = new SavePowerConfig();

        UICustomization uiCustomization = new UICustomization();
        uiCustomization.hideKeyboardOnEnterConsult = true;
        uiCustomization.inputTextSize = 15;
        uiCustomization.hideAudio = true;
        uiCustomization.hideEmoji = true;
        uiCustomization.msgBackgroundColor = Color.parseColor("#F9F9F9");
        uiCustomization.titleBackgroundColor = Color.parseColor("#FFFFFF");
        uiCustomization.topTipBarTextColor = Color.parseColor("#454C57");
        uiCustomization.msgItemBackgroundLeft = R.drawable.ic_left_chat_bg;
        uiCustomization.msgItemBackgroundRight = R.drawable.ic_right_chat_bg;
        uiCustomization.textMsgSize = 14;
        uiCustomization.textMsgColorLeft = Color.parseColor("#454C57");
        uiCustomization.textMsgColorRight = Color.parseColor("#454C57");
        uiCustomization.inputTextSize = 14;
        uiCustomization.inputTextColor = Color.parseColor("#454C57");
        uiCustomization.leftAvatar = "http://moli2017.oss-cn-zhangjiakou.aliyuncs.com/user/msg_img_001.png";
        if (UserManager.ins().isLogin()) {
            uiCustomization.rightAvatar = UserManager.ins().getLoginUser().getImage();

            YSFUserInfo userInfo = new YSFUserInfo();
            userInfo.userId = UserManager.ins().getUserId();
            userInfo.data = "[ {\"key\":\"real_name\", \"value\": \"" + UserManager.ins().getLoginUser().getName() + "\"},  {\"key\":\"mobile_phone\", \"hidden\":false,\"value\":\"" + UserManager.ins().getLoginUser().getPhone() + "\"}, {\"key\":\"avatar\", \"value\": \"" + UserManager.ins().getLoginUser().getImage() + "\"}]";
            Unicorn.setUserInfo(userInfo);
        }
        options.uiCustomization = uiCustomization;

        return options;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        String articleId = String.valueOf(dataList.get(position).getUrl());
        Article article = new Article();
        article.setId(articleId);
        ArticleDetailActivity.start(this, article, false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
